

from random import randint
from block import Block
from process import Process

n = 5
processList = []
blockList = []
processStr = ""
blockStr = ""

def init(n):
    # 清空列表  防止多次点击执行按钮 导致列表元素叠加
    processList.clear()
    blockList.clear()
    for i in range(n):
        process = Process("进程{}".format(i+1), randint(20, 150))
        processList.append(process)

        block = Block("内存块{}".format(i+1), randint(30, 200), hex(randint(500, 1500)), [])
        blockList.append(block)

    return processList, blockList

# 排序
def getFirstLink(blockList):
    blockList.sort(key=lambda block: block.addr, reverse=False)
    return blockList


# 执行首次适应分配算法
def FF(processList, blockList):
    index = 0
    flag = True
    for i in range(n):
        for block in blockList:
            if processList[index].space <= block.space:
                block.addProcess(processList[index])
                processList.pop(index)
                flag = False
                break
        if flag:
            index += 1
    return processList, blockList

def List2Str(lst):
    string = ""
    for item in lst:
        string += (str(item)+"\n")
    return string

def main(n):
    processList, blockList = init(n)
    blockList = getFirstLink(blockList)

    print(List2Str(processList))

    processList, blockList = FF(processList, blockList)
    if processList:
        print("没有分配完, 剩余", processList)
    else:
        print("分配完了")
    print(blockList)

if __name__ == '__main__':
    main(5)